<template>
  <div id="person-list" class="app-container full-height relative">
    <div class="full-width" style="min-height: 750px">
      <div class="relative">
        <list-search-bar
          ref="searchbar"
          :search-rule="searchRule"
          :showClear="searchRule.length > 0"
          @submit="getList($event, pageInfo)"
          @add="showEdit()"
          @update:value="searchData = $event"
        >
          <!-- <template slot="btn-group-right">
            <el-button size="mini" type="warning" @click="exportList"
              >导出</el-button
            >
          </template> -->
        </list-search-bar>
      </div>

      <list-table
        :showEdit="permissions.edit"
        @edit="showEdit($event)"
        @remove="remove"
        :showRemove="permissions.remove"
        v-loading="listLoading"
        :listRule="editRule"
        :listData="listData"
        btnGroupWidth="350px"
        :tableHeight="tableHeight - 30"
        :fixedRight="true"
        :showTool="true"
        :exportApi="exportApi"
        :exportSearch="exportSearch"
        :convertList="convertList"
      >
        <template slot="btn-group" slot-scope="{ row }">
          <!-- <el-button
            slot="reference"
            size="mini"
            :type="isRole(row) ? 'info' : 'primary'"
            @click="isRole(row) ? yunweiNone : yunweiSet(row)"
            >分配运维
          </el-button> -->
          <el-button
            slot="reference"
            size="mini"
            type="primary"
            @click="roleSet(row)"
            >分配角色
          </el-button>
        </template>
      </list-table>
      <pagination
        :page-sizes="[20]"
        :page-size="pageInfo.size"
        :current-page="pageInfo.page"
        :total="pageInfo.total"
        @pagination="getList(searchData, { ...pageInfo, page: $event.page })"
      />
    </div>
    <back-to-top
      :visibility-height="300"
      :back-position="0"
      transition-name="fade"
    />
    <el-dialog
      :close-on-click-modal="false"
      width="500px"
      v-dialogDrag
      :visible.sync="editDialog"
      v-loading="editLoading"
      custom-class="widget-dialog widget-form center no-margin color-white black-bg2"
      title="编辑账号"
    >
      <form-create
        v-model="editFormInstance"
        :value.sync="editData"
        :rule="editRule"
        :option="editOptions"
      />
      <template slot="footer">
        <el-button size="mini" type="primary" @click="update(editData)"
          >提交</el-button
        >
        <el-button size="mini" @click="reset">重置</el-button>
      </template>
    </el-dialog>

    <!-- Topo -->
    <el-dialog
      :close-on-click-modal="false"
      width="600px"
      v-dialogDrag
      :visible.sync="topoDialog"
      v-loading="topoLoading"
      custom-class="widget-dialog widget-form center no-margin color-white black-bg2"
      :title="topoTitle"
    >
      <div class="widget-tree">
        <el-tree
          v-if="topoDialog"
          ref="treeNode"
          show-checkbox
          :data="currentTopo"
          :default-expanded-keys="['#']"
          :props="defaultProps"
          :render-after-expand="true"
          check-on-click-node
          :expand-on-click-node="false"
          style="padding: 10px"
          @check-change="topoChange"
          :default-checked-keys="topoShowList"
          node-key="id"
        >
        </el-tree>
      </div>
      <template slot="footer">
        <el-button size="mini" type="primary" @click="update(editData)"
          >提交</el-button
        >
        <!-- <el-button size="mini" @click="reset">重置</el-button> -->
      </template>
    </el-dialog>

    <!-- 角色 -->
    <el-dialog
      :close-on-click-modal="false"
      width="600px"
      v-dialogDrag
      :visible.sync="roleDialog"
      v-loading="roleLoading"
      custom-class="widget-dialog widget-form center no-margin color-white black-bg2"
      title="分配角色"
    >
      <div class="widget-tree">
        <el-tree
          v-if="roleDialog"
          ref="roleNode"
          show-checkbox
          check-on-click-node
          :data="roleList"
          :props="roleProps"
          :render-after-expand="true"
          :expand-on-click-node="false"
          @check-change="roleChange"
          :default-checked-keys="roleCheck"
          node-key="id"
          check-strictly
        >
        </el-tree>
      </div>
      <template slot="footer">
        <el-button size="mini" type="primary" @click="roleUpdate"
          >提交</el-button
        >
      </template>
    </el-dialog>
    <!-- 运维 -->
    <el-dialog
      :close-on-click-modal="false"
      width="600px"
      v-dialogDrag
      :visible.sync="yunweiDialog"
      v-loading="roleLoading"
      custom-class="widget-dialog widget-form center no-margin color-white black-bg2"
      title="分配运维"
    >
      <div class="widget-tree">
        <el-tree
          v-if="yunweiDialog"
          ref="operationRoleNode"
          show-checkbox
          :data="OperationRoleList"
          :props="operationRoleProps"
          :render-after-expand="true"
          :expand-on-click-node="false"
          check-on-click-node
          class="black-bg color-white"
          @check-change="operationRroleChange"
          :default-checked-keys="operationroleCheck"
          node-key="operationRoleId"
          check-strictly
        >
        </el-tree>
      </div>
      <template slot="footer">
        <el-button size="mini" type="primary" @click="operationRoleUpdate"
          >提交</el-button
        >
      </template>
    </el-dialog>
  </div>
</template>

<script>
import {
  sysGetUserList as searchApi, //获取列表的api
  sysAddUser as addApi, //新增数据的api
  sysEditUser as updateApi, //更新、新增数据的api
  sysDeleteUser as removeApi, //删除数据的api
  sysGetRoleByUserId as detailApi, //详情api
  sysGetRoleList, //获取角色列表
  sysGetOperationRoleList, //获取运维角色列表
  sysInsertUserRole, //分配角色
  sysGetRoleByUserId,
  sysInsertUserOperationRole, //分配运维角色
  sysGetOperationRoleByUserId, //运维角色
  departmentGetList,
  excelGetAllUserList,
  sysGetAllOperationRoleList,
  companyGetCompanyTreeAllList
} from "@/api";
import {
  editRule,
  searchRule,
  isVIPList,
  isDeleteList
} from "@/formRules/system/PersonListRules";
import { editFormOptions, getData } from "@/formRules";
import checkPermission from "@/utils/permission";
import { isDev } from "@/configurations.js";
import { translateDataToTree } from "@/utils/parentSon";
import { mapState } from "vuex";
import mixin from "@/mixins/companySet";
import { xlsxExport } from "@/utils/csv";
import tableAutoHeight from "@/mixins/tableAutoHeight";
export default {
  name: "PersonList",
  configurations: {
    title: "账号管理",
    isDefault: true,
    show: true
  },
  mixins: [mixin, tableAutoHeight],
  data() {
    return {
      exportApi: searchApi,
      exportSearch: {},
      editRule: editRule(),
      listData: [],
      searchRule: searchRule(),
      searchData: {}, //搜索表单数据
      editFormInstance: {},
      editData: {},
      editOptions: editFormOptions(),
      editDialog: false,
      editLoading: false,
      listLoading: false,
      toReview: 0,
      pageInfo: {
        page: 1,
        size: 20,
        total: 0
      },
      permissionList: [], //权限列表
      defaultProps: {
        children: "children",
        label: "text"
      },
      roleProps: {
        children: "children",
        label: "roleName"
      },
      operationRoleProps: {
        children: "children",
        label: "operationRoleName"
      },
      topoList: [],
      topoDialog: false,
      topoLoading: false,
      topoShowList: [],
      roleList: [],
      roleDialog: false,
      roleLoading: false,
      roleCheck: [],
      yunweiDialog: false,
      OperationRoleList: [],
      operationroleCheck: [],
      lockVal: 0,
      topoTitle: "分配TOPO图",
      companyTreeList: [],
      convertList: []
    };
  },
  // 在路由导航进来之前检查权限
  beforeRouteEnter(from, to, next) {
    const permissionList = checkPermission(to.path);
    if (permissionList.length) {
      next(vm => {
        vm.permissionList = permissionList;
      });
      return;
    }
    next({
      name: "403"
    });
  },
  watch: {
    "searchData.companyId"(n) {
      this.getOriRoleList();
    },
    "editData.companyId"(n) {
      console.log("公司Id------------------");
      console.log(n);
      this.initCompany();
    }
  },
  mounted() {
    this.GetCompanyTreeAllList();
    this.getYunweiList();
    this.getCompany();

    if (this.isAdmin) {
      this.searchRule = searchRule(this.isAdmin);
      this.editRule = editRule(this.isAdmin);
    }

    this.topoList = this.topoList.filter((e, index) => index == 0);
    this.getRoleList();
    this.searchReview();
  },
  computed: {
    ...mapState(["companyId", "isAdmin", "user"]),
    userName() {
      return this.user.username;
    },
    // 根据获取的权限列表此处返回各个权限的显示与否
    permissions() {
      return ["edit", "remove", "add"].reduce((pre, cur) => {
        pre[cur] = true;
        // isDev ? true : this.permissionList.includes(cur);
        return pre;
      }, {});
    },
    currentTopo() {
      return translateDataToTree(this.topoList);
    }
  },
  methods: {
    isRole(row) {
      let data = false;
      if (row.roleName == "客服主管" || row.roleName == "客服人员") {
        data = true;
      }
      return data;
    },
    searchReview() {
      this.pageInfo.page = 1;
      let data = {
        companyId: this.companyId ? this.companyId : this.searchData.companyId
      };
      this.getList(data, this.pageInfo);
    },

    /**
     * @name 查询列表
     * @param {Object} query 查询参数，一般为this.searchData
     * @param {Object} pageInfo 页面参数，包括pageSize和pageNo
     * @description 调用成功则刷新listData
     */
    getList(query, pageInfo) {
      this.listLoading = true;
      const queryParam = {
        ...pageInfo,
        ...query
      };
      delete queryParam.total;
      if (!queryParam.companyId) {
        // queryParam.companyId=this.companyId
      }
      this.exportSearch = Object.assign({}, queryParam);
      searchApi(queryParam)
        .then(({ code, data }) => {
          //   console.log(data);
          if (code == 200) {
            this.listData = data.list;
            this.listData.forEach(e => {
              e.companyId = Number(e.companyId);
            });
            this.pageInfo.total = data.total;
            this.exportSearch.page = 1;
            this.exportSearch.size = data.total;
            this.$nextTick(() => {
              this.convertList = [
                //需要替换中文字段
                {
                  field: "isVip",
                  options: [{ label: "未绑定", value: "无" }].concat(
                    isVIPList()
                  )
                },
                { field: "isDelete", options: isDeleteList() }
              ];
            });
          }
        })
        .finally(() => {
          this.listLoading = false;
        });
    },
    /**
     * @name 编辑表单
     * @param {Object} row 表单数据，新增时为空
     * @description 调用成功打开表单对话框
     */
    showEdit(row) {
      //   console.log("row", row);
      if (!row) {
        this.editData = getData(editRule());
        this.editData.companyId = this.searchData.companyId;
        this.editDialog = true;
        this.editRule.forEach(e => {
          if (e.field == "userName" || e.field == "mobile") {
            e.props.disabled = false;
          }
        });
        this.$nextTick(() => {
          this.editFormInstance.updateRule("treeIdList", {
            options: this.companyTreeList
          });
        });
      } else {
        // detailApi({ id: row.id }).then((res) => {
        //   const { data } = res;
        this.editData = row;
        this.editDialog = true;
        this.editRule.forEach(e => {
          if (e.field == "userName" || e.field == "mobile") {
            e.props.disabled = true;
          }
        });
        this.$nextTick(() => {
          this.editFormInstance.updateRule("treeIdList", {
            options: this.companyTreeList
          });
        });
      }
    },
    /**
     * @name 更新数据
     * @param editData 编辑的数据体
     * @description 调用成功关闭对话框并且刷新表单
     */
    update(editData) {
      if (!this.validation()) return;
      this.editLoading = true;

      if (!editData.companyId) {
        delete editData.companyId;
      }
      if (editData.id) {
        updateApi(editData)
          .then(({ code, msg }) => {
            if (code == 200) {
              this.$notified.success({
                message: "更新数据成功!"
              });
              this.getList(this.searchData, this.pageInfo);
              this.editDialog = false;
              this.topoDialog = false;
            } else {
              this.$notified.error({
                message: msg
              });
            }
          })
          .finally(() => (this.editLoading = false));
      } else {
        addApi(editData)
          .then(({ code, data, msg }) => {
            if (code == 200) {
              this.$notified.success({
                message: "新增数据成功"
              });
              this.getList(this.searchData, this.pageInfo);
              this.editDialog = false;
            } else {
              this.$notified.error({
                message: msg
              });
            }

            // this.$refs?.searchbar.reset();
          })
          .finally(() => (this.editLoading = false));
      }
    },
    /**
     * @name 表单验证
     * @description 如果有则在此处写入逻辑
     * @returns {Boolean} 表单验证结果
     */
    validation() {
      let satate = false;
      this.editFormInstance.validate((valid, fail) => {
        satate = valid;
      });
      return satate;
    },
    /**
     * @name 删除数据项
     * @description 成功后会刷新列表
     */
    remove(row) {
      this.listLoading = true;
      removeApi({
        userId: row.id
      })
        .then(() => {
          this.$notified.success({
            message: "删除成功"
          });
          this.getList(this.searchData, this.pageInfo);
        })
        .finally(() => {
          this.listLoading = false;
        });
    },
    /**
     * @name 重置表单数据
     */
    reset() {
      this?.editFormInstance?.resetFields();
    },
    handleTreeNodeClick(e) {},
    roleSet(item) {
      this.editData = item;
      if (item.topoId) {
        this.topoShowList = item.topoId.split(",");
        this.editData.topoId = item.topoId;
      } else {
        this.topoShowList = [];
      }
      sysGetRoleByUserId({ userId: item.id }).then(({ data }) => {
        let roleL = [];
        if (data && data.length) {
          data.forEach(element => {
            roleL.push(element.id);
          });
        }
        this.roleCheck = roleL;
        this.$nextTick(() => {
          this.roleDialog = true;
          //有配置运维的就不能是客服
          this.roleList.forEach(e => {
            if (
              (e.id == 8 && item.operationRoleName) ||
              (e.id == 6 && item.operationRoleName)
            ) {
              e.disabled = true;
            }
          });
        });
      });
    },
    async GetCompanyTreeAllList() {
      let { data } = await companyGetCompanyTreeAllList({});
      let list = [];
      data.forEach(e => {
        list.push({ value: e.companyTreeId, label: e.companyTreeName });
      });
      this.companyTreeList = list;
    },
    yunweiNone() {
      return false;
    },
    yunweiSet(item) {
      this.editData = item;
      this.getOriRoleList(item.companyId);
      if (item.topoId) {
        this.topoShowList = item.topoId.split(",");
        this.editData.topoId = item.topoId;
      } else {
        this.topoShowList = [];
      }
      sysGetOperationRoleByUserId({ userId: item.id }).then(
        ({ data, code, msg }) => {
          let roleL = [];
          if (data && data.length) {
            data.forEach(element => {
              roleL.push(element.operationRoleId);
            });
          }
          this.operationroleCheck = roleL;
          console.log("roleL");
          console.log(roleL);
          this.$nextTick(() => {
            this.yunweiDialog = true;
          });
        }
      );
    },
    roleUpdate() {
      let param = {
        list: [],
        userId: this.editData.id
      };
      let list = this.$refs.roleNode.getCheckedKeys();
      if (list.length) {
        list.forEach((el, index) => {
          param.list.push(el);
        });
      }
      console.log(param);
      //   debugger;
      this.roleLoading = true;
      sysInsertUserRole(param)
        .then(({ code, msg }) => {
          console.log(code);
          if (code == 200) {
            this.roleDialog = false;
            this.$notified.success({
              message: "角色分配成功!"
            });
            this.getList(this.searchData, this.pageInfo);
          } else {
            this.$notified.error({
              message: msg
            });
          }
        })
        .finally(() => {
          this.roleLoading = false;
        });
    },
    operationRoleUpdate() {
      let param = {
        list: [],
        userId: this.editData.id
      };
      let list = this.$refs.operationRoleNode.getCheckedKeys();
      if (list.length) {
        list.forEach((el, index) => {
          param.list.push(el);
        });
      }
      this.roleLoading = true;
      sysInsertUserOperationRole(param)
        .then(({ code, msg }) => {
          if (code == 200) {
            this.$notified.success({
              message: "成功分配运维角色"
            });
            this.getList(this.searchData, this.pageInfo);
            this.yunweiDialog = false;
          } else {
            if (code != 200) {
              this.$message.error(msg);
              return false;
            }
          }
        })
        .finally(() => {
          this.roleLoading = false;
        });
    },
    topoChange() {
      let list = this.$refs.treeNode.getCheckedKeys();
      this.topoShowList = list;
      if (this.lockVal == 1) {
        this.editData.topoId = list.toString();
      } else if (this.lockVal == 2) {
        this.editData.groupId = list.toString();
      } else if (this.lockVal == 3) {
        this.editData.repTableId = list.toString();
      }
    },
    roleChange(data, checked, tree) {
      if (checked) {
        this.$refs.roleNode.setCheckedNodes([data]);
      }
    },
    operationRroleChange(data, checked, tree) {
      if (checked) {
        this.$refs.operationRoleNode.setCheckedNodes([data]);
      }
    },
    getRoleList() {
      sysGetRoleList({ page: 1, size: 100, userName: this.userName })
        .then(({ code, data }) => {
          if (code == 200) {
            this.roleList = data.list;
          }
        })
        .finally(() => {
          this.listLoading = false;
        });
      this.getOriRoleList();
    },
    initCompany() {
      this.initDepartmentId();
    },
    async initDepartmentId() {
      let params = {
        page: 1,
        size: 100,
        companyId: this.editData.companyId
      };
      let { data } = await departmentGetList(params);
      let list = [];
      data.forEach(e => {
        list.push({ value: e.id, label: e.name });
      });
      this.editFormInstance.updateRule("departmentId", { options: list });
    },
    getOriRoleList(companyId) {
      sysGetOperationRoleList({
        page: 1,
        size: 100,
        companyId: companyId || this.companyId || this.searchData.companyId
      })
        .then(({ code, data }) => {
          if (code == 200) {
            this.OperationRoleList = data.list;
          }
        })
        .finally(() => {
          this.listLoading = false;
        });
    },
    exportList() {
      excelGetAllUserList({ companyId: this.searchData.companyId }).then(
        ({ data }) => {
          //   data.forEach(e => {
          //     e.isVipText = isVIPList().find(i => i.value == e.isVip).label;
          //   });
          let titleArray = editRule()
            .filter(i => i.tableVisible)
            .map(i => i.title);
          let dataArray = data.map(
            ({
              companyName,
              bumenName,
              gangwei,
              userName,
              customName,
              roleName,
              isVipText,
              mobile,
              ccid
            }) => {
              return [
                companyName,
                bumenName,
                gangwei,
                userName,
                customName,
                roleName,
                isVipText,
                mobile,
                ccid
              ];
            }
          );

          xlsxExport("账号信息表.xlsx", titleArray, dataArray);
        }
      );
    },
    async getYunweiList() {
      let { data, code } = await sysGetAllOperationRoleList();
      let list = [];
      if (data.length) {
        data.forEach(e => {
          list.push({ value: e, label: e });
        });
      }

      this.searchRule[1].options = list;
    }
  }
};
</script>

<style lang="scss" scoped>
@import "@/styles/variables.scss";
#idName {
  position: relative;
  overflow: hidden;
}
</style>
